﻿package com.petermacko.utils.interactive {
	import flash.display.*;
	import flash.events.*;
	import flash.utils.*;
	
	import com.petermacko.events.MouseIdleMonitorEvent;	

	//A small utility class that allows you to see if a user has been inactive with the mouse.  The class will dispatch a custom MouseIdleMonitorEvent with a params object that contains the time the user has been idle, in milliseconds.
	public class MouseIdleMonitor extends EventDispatcher
	{
		private var stg:Stage; //stage
		private var intm:int; //inactiveTime
		private var t:Timer; //timer
		private var idtm:int; //idleTime
		private var ima:Boolean; //isMouseActive

		/**
		 * Creates an instance of hte MouseIdleMonitor class.  
		 * 
		 * <p>
		 * The class will dispatch two events:
		 * <ul>
		 * <li>MouseIdleMonitorEvent.MOUSE_ACTIVE: Dispatched when the mouse becomes active, repeatedly on MOUSE_MOVE</li>
		 * <li>MouseIdleMonitorEvent.MOUSE_IDLE: Dispatched when the mouse becomes inactive, params object holds idle time ("time")</li>
		 * </ul>
		 * </p>
		 * 
		 * @param stage The stage object to use for the mouse tracking
		 * @param inactiveTime The time, in milliseconds, to check if the user is active or not (default: 1000)
		 * 
		 * @return void
		 */
		public function MouseIdleMonitor(stg:Stage,intm:int = 1000):void {
			super();
			this.stg = stg;
			this.intm = intm;
			this.t = new Timer(this.intm);
		}
		//Starts the MouseIdleMonitor and allows it to check for mouse inactivity.
		public function start():void {
			this.stg.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			this.t.addEventListener(TimerEvent.TIMER, onTimer);
			this.t.start();
		}
		//Stops the MouseIdleMonitor from checking for mouse inactivity.
		public function stop():void {
			this.idtm = 0;
			this.t.reset();
			this.stg.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			this.t.removeEventListener(TimerEvent.TIMER, onTimer);
		}
		//Reset the timer if the mouse moves, user is active.
		private function onMouseMove(e:MouseEvent):void {
			this.ima = true;
			this.idtm = 0;
			this.t.reset();
			this.t.start();
			this.dispatchEvent(new MouseIdleMonitorEvent(MouseIdleMonitorEvent.MOUSE_ACTIVE, {}));
		}
		//Runs if the user is inactive, sets the idle time.
		private function onTimer(e:TimerEvent):void {
			this.ima = false;
			this.idtm += this.intm;
			this.dispatchEvent(new MouseIdleMonitorEvent(MouseIdleMonitorEvent.MOUSE_IDLE, {time:this.idtm}));
		}
		//Returns a boolean value that specifies if the mouse is active or not.
		public function get ima():Boolean	{
		    return this.ima;
		}
		//Returns an integer representing the amount of time the user's mouse has been inactive, in milliseconds
		public function get idtm():int {
		    return this.idtm;
		}
		override public function toString():String {
			return getQualifiedClassName(this);
		}
	}
}